package com.atde._03_creational_design_patterns.prototype.deepclone;


import java.io.*;

/**
 * @BelongsProject: hsp_java_design_mode
 * @BelongsPackage: com.atde._03_creational_design_patterns.prototype.deepclone
 * @Author: Del
 * @CreateTime: 2025-06-17  18:35
 * @Description: 原型模式 -- 原型类
 * @Version: 1.0
 */
public class DeepProtoType implements Cloneable, Serializable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }

    // 深拷贝 -- 方式1 使用clone 方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 完成基本数据类型的克隆
        deep = super.clone();
        // 对引用类型的属性单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    // 深拷贝 -- 方式2 通过对象的序列化实现（推荐）
    public Object deepClone() {
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            // 序列化操作
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this); // 写入当前对象

            // 反序列化操作
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                assert bos != null;
                bos.close();
                assert oos != null;
                oos.close();
                assert bis != null;
                bis.close();
                assert ois != null;
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
